/* Edge.java */

/**
 * Edge.java represents a pair of objects that act as vertices in a
 * WUGraph (weighted, undirected graph).  The purpose of an Edge is to
 * act as a key in Java's built-in Hashtable class.  The hashCode() and
 * equals() functions, which are called by Java's hash tables, are designed
 * so that the order of the two objects is immaterial; (u, v) is the same as
 * (v, u).
 * 
 * This is essentially a copy of VertexPair in the graph package.
 */

class Edge implements Comparable<Edge> {
	protected Object vertex1;
	protected Object vertex2;
	protected int weight;

	protected Edge(Object v1, Object v2, int weight){
		vertex1 = v1;
		vertex2 = v2;
		this.weight = weight;
	}

	protected Edge(Object v1, Object v2){
		this(v1, v2, -1);
	}

	/**
	 * hashCode() returns a hashCode equal to the sum of the hashCodes of each
	 * of the two objects of the pair, so that the order of the objects will not
	 * affect the hashCode. Self-edges are treated differently: we don't add an
	 * object's hashCode to itself, since the result would always be even. We
	 * add one to the hashCode so that a self-edge will not collide with the
	 * object itself if vertices and edges are stored in the same hash table.
	 */
	public int hashCode() {
		if (vertex1.equals(vertex2)) {
			return vertex1.hashCode() + 1;
		} else {
			return vertex1.hashCode() + vertex2.hashCode();
		}
	}

	/**
	 * equals() returns true if this VertexPair represents the same unordered
	 * pair of objects as the parameter "o". The order of the pair does not
	 * affect the equality test, so (u, v) is found to be equal to (v, u).
	 */
	public boolean equals(Object o) {
		if (o instanceof Edge) {
			return ((vertex1.equals(((Edge) o).vertex1)) && (vertex2
					.equals(((Edge) o).vertex2)))
					|| ((vertex1.equals(((Edge) o).vertex2)) && (vertex2
							.equals(((Edge) o).vertex1)));
		} else {
			return false;
		}
	}

	@Override
	public int compareTo(Edge e) {
		return weight - e.weight;
	}	
	
}
